﻿using NPOI.HSSF.UserModel;
using OMG.Fill.Potato.Model.Ent;
using OMG.Fill.Potato.Services;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Http;
namespace OMG.Fill.Potato.Model.UI.Controllers
{
    public class PotSeedController : ApiController
    {
        PotSeedServices potSeedServices = new PotSeedServices();
        
        //[ApiActionAuthorize("获取马铃薯种薯生产情况表分页列表对象操作")]
        //[ApiActionException]
        public Pager<List<PotSeedEntity>> PostPageList(PotSeedQuery query)
        {
            return potSeedServices.GetPageList(query);
        }
        //[ApiActionAuthorize("新增马铃薯种薯生产情况表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Post(List<PotSeedEntity> list) {
            return potSeedServices.AddInfo(list);
        }
        //[ApiActionAuthorize("修改马铃薯种薯生产情况表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Put(PotSeedEntity model)
        {
            return potSeedServices.UpdateInfo(model);
        }
        //[ApiActionAuthorize("删除马铃薯种薯生产情况表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Delete(string id)
        {
            return potSeedServices.DeleteInfo(id);
        }
        //[ApiActionAuthorize("获取马铃薯种薯生产情况表指定对象操作")]
        //[ApiActionException]
        public ResResult<List<PotSeedEntity>> Get(string ReportId)
        {
            return potSeedServices.GetModel(ReportId);
        }

        public ResResult<MyReportModel> Get(string AreaCode,string FillInYear)
        {
            return potSeedServices.GetModel(AreaCode, FillInYear);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="FillInYear"></param>
        /// <param name="AreaName"></param>
        public void GetExcelData(string FillInYear, string AreaCode)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            string strFileName = "（三）" + FillInYear + "年" + "-" + AreaName + "-马铃薯种薯生产情况表.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            curContext.Response.BinaryWrite(Method(FillInYear, AreaCode).GetBuffer());
            curContext.Response.End();
        }
        /// <summary>
        /// 获取导出数据
        /// </summary>
        /// <param name="ReportId"></param>
        /// <returns></returns>
        public MemoryStream Method(string FillInYear, string AreaCode)
        {
            FileStream file = null;
            MemoryStream ms = new MemoryStream();
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\PotDownload.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("PotSeed") as HSSFSheet;//读取模板所在sheet位置
            List<PotSeedEntity> pagelist = (List < PotSeedEntity > )potSeedServices.GetModel(AreaCode, FillInYear).model.list;//数据获取
            try
            {
                if (pagelist.Count != 0)
                {
                    HSSFRow row = (HSSFRow)sheet.GetRow(3);//读取模板第4行                   
                    int startRow = 3;
                    for (int j = 0; j < pagelist.Count; j++)
                    {
                        HSSFRow datarow = (HSSFRow)sheet.CreateRow(j + startRow);                      
                        datarow.CreateCell(0).SetCellValue(pagelist[j].ZPyield == null ? "" : string.Format("{0:N4}", pagelist[j].ZPyield));
                        datarow.CreateCell(1).SetCellValue(pagelist[j].ZPvariety == null ? "" :  pagelist[j].ZPvariety);
                        datarow.CreateCell(2).SetCellValue(pagelist[j].YYZdpArea == null ? "" : string.Format("{0:N2}", pagelist[j].YYZdpArea));
                        datarow.CreateCell(3).SetCellValue(pagelist[j].YYZsingleArea == null ? "" : string.Format("{0:N2}", pagelist[j].YYZsingleArea));
                        datarow.CreateCell(4).SetCellValue(pagelist[j].YYZavgYield == null ? "" : string.Format("{0:N2}", pagelist[j].YYZavgYield));
                        datarow.CreateCell(5).SetCellValue(pagelist[j].YYZvariety == null ? "" :pagelist[j].YYZvariety);
                        datarow.CreateCell(6).SetCellValue(pagelist[j].YYZplantTimes == null ? "" :  pagelist[j].YYZplantTimes.ToString());
                        datarow.CreateCell(7).SetCellValue(pagelist[j].YZarea == null ? "" : string.Format("{0:N2}", pagelist[j].YZarea));
                        datarow.CreateCell(8).SetCellValue(pagelist[j].YZmuYield == null ? "" : string.Format("{0:N2}", pagelist[j].YZmuYield));
                        datarow.CreateCell(9).SetCellValue(pagelist[j].YZyyzOrigin == null ? "" :pagelist[j].YZyyzOrigin);
                        datarow.CreateCell(10).SetCellValue(pagelist[j].YZvariety == null ? "" :pagelist[j].YZvariety);
                        datarow.CreateCell(11).SetCellValue(pagelist[j].YZoriginPlace == null ? "" : pagelist[j].YZoriginPlace);
                        datarow.CreateCell(12).SetCellValue(pagelist[j].YJZarea == null ? "" : string.Format("{0:N2}", pagelist[j].YJZarea));
                        datarow.CreateCell(13).SetCellValue(pagelist[j].YJZmuYield == null ? "" : string.Format("{0:N2}", pagelist[j].YJZmuYield));
                        datarow.CreateCell(14).SetCellValue(pagelist[j].YJZvariety == null ? "" :  pagelist[j].YJZvariety);
                        datarow.CreateCell(15).SetCellValue(pagelist[j].YJZoriginPlace == null ? "" : pagelist[j].YJZoriginPlace);
                        datarow.CreateCell(16).SetCellValue(pagelist[j].Remark == null ? "" : pagelist[j].Remark);
                        for (int i = 0; i <= 16; i++)
                        {
                            datarow.GetCell(i).CellStyle = row.GetCell(i).CellStyle;
                        }
                    }
                    sheet.CopyTo(workbook, "Sheet1", true, true);
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;

                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.ToString().Trim());
            }
            return ms;
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="ReportId"></param>
        /// <returns></returns>
        public ResResult<int> PostImportData(string ReportId)
        {
            ResResult<int> obj = new ResResult<int>();
            ResResult<int> SingleObj = new ResResult<int>();
            HttpContext curContext = HttpContext.Current;
            HttpFileCollection files = curContext.Request.Files;

            if (curContext.Request.Files.Count != 0)
            {
                HttpPostedFile upfile = files[0];
                if (upfile != null && upfile.ContentLength > 0)
                {
                    string temppath = curContext.Server.MapPath("~/App_Data/temppath");
                    if (!Directory.Exists(temppath))//判断文件夹是否存在 
                    {
                        Directory.CreateDirectory(temppath);//不存在则创建文件夹 
                    }
                    string filetype = Path.GetExtension(upfile.FileName);
                    string filenewName = Guid.NewGuid().ToString().Replace("-", "") + filetype;
                    string strpath = Path.Combine(temppath, filenewName);
                    upfile.SaveAs(strpath);
                    List<PotSeedEntity> list = potSeedServices.ExcelToModel(strpath, filetype, ReportId);
                    if (list != null && list.Count > 0&& potSeedServices.AddInfo(list).status==DefaultKey.SuccessResult)
                    {
                        obj.status = DefaultKey.SuccessResult; ;
                        obj.message = "数据导入成功！！";
                    }
                    else
                    {
                        obj.status = DefaultKey.ErrorResult; ;
                        obj.message = "数据导入失败！！";
                    }

                    Directory.Delete(temppath, true);
                }
            }

            return obj;
        }
        public ResResult<List<SeedStatisModel>> GetStatisListData(string AreaCode, string FillInYear)
        {
            return potSeedServices.getStatisListData(AreaCode, FillInYear);
        }

        /// <summary>
        /// 统计导出
        /// </summary>
        /// <param name="AreaCode"></param>
        /// <param name="FillInYear"></param>
        public void GetStatisExcel(string AreaCode, string FillInYear)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            string strFileName = "（三）" + FillInYear + "年" + "-" + AreaName + "-马铃薯种薯生产情况汇总表.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            //curContext.Response.AppendHeader("Content-Disposition",
            //   "attachment;filename=" + strFileName);
            curContext.Response.BinaryWrite(loadStatis(AreaCode, FillInYear).GetBuffer());
            curContext.Response.End();
        }

        public MemoryStream loadStatis(string AreaCode, string FillInYear)
        {
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\PotStatisLoad.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet tempsheet = templateBook.GetSheet("PotSeed") as HSSFSheet;//读取模板所在sheet位置
            List<SeedStatisModel> pagelist = (List<SeedStatisModel>)potSeedServices.getStatisListData(AreaCode, FillInYear).model;//数据获取

            HSSFRow row = (HSSFRow)tempsheet.GetRow(3);//读取模板第4行
           // var style = row.GetCell(1).CellStyle;//读取模板第5行第2单元格样式并保存
           // row.GetCell(1).CellStyle = style;//对第3行第2单元格设置原来样式

            HSSFSheet sheet = CopyToSheet(tempsheet, pagelist);
            AreaServices areaServices = new AreaServices();
            string areaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            sheet.CopyTo(workbook, areaName, true, true);

           

            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }

        public HSSFSheet CopyToSheet(HSSFSheet sheet, List<SeedStatisModel> pagelist)
        {
            HSSFRow row = (HSSFRow)sheet.GetRow(3);
            if (pagelist.Count > 0)
            {
                int startRow = 3;
                for (int j = 0; j < pagelist.Count; j++)
                {
                    HSSFRow datarow = (HSSFRow)sheet.CreateRow(j + startRow);
                    datarow.CreateCell(0).SetCellValue(pagelist[j].AreaName == null ? "" : pagelist[j].AreaName);
                    datarow.CreateCell(1).SetCellValue(pagelist[j].ZPyield == null ? "" : string.Format("{0:N4}", pagelist[j].ZPyield));
                    datarow.CreateCell(2).SetCellValue(pagelist[j].YYZdpArea == null ? "" : string.Format("{0:N2}", pagelist[j].YYZdpArea));
                    datarow.CreateCell(3).SetCellValue(pagelist[j].YZarea == null ? "" : string.Format("{0:N2}", pagelist[j].YZarea));
                    datarow.CreateCell(4).SetCellValue(pagelist[j].YZYield == null ? "" : string.Format("{0:N2}", pagelist[j].YZYield));
                    //datarow.CreateCell(5).SetCellValue(pagelist[j].YZmuYield == null ? "" : string.Format("{0:N2}", pagelist[j].YZmuYield));
                    datarow.CreateCell(5).SetCellValue(pagelist[j].YJZarea == null ? "" : string.Format("{0:N2}", pagelist[j].YJZarea));
                    datarow.CreateCell(6).SetCellValue(pagelist[j].YJZYield == null ? "" : string.Format("{0:N2}", pagelist[j].YJZYield));
                   // datarow.CreateCell(8).SetCellValue(pagelist[j].YJZmuYield == null ? "" : string.Format("{0:N2}", pagelist[j].YJZmuYield));
                    for (int i = 0; i <= 6; i++)
                    {
                        datarow.GetCell(i).CellStyle = row.GetCell(i).CellStyle;
                    }
                }
            }
            return sheet;
        }



    }
}